#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "Edit_Membership_Data.h"
#include "member.h"
#include "common.h"



void Edit_Membership_Data(void)
{
    char card_num[11];
    printf("\n请输入要修改的会员卡号：");
    scanf("%s", card_num);

    FILE* fp = fopen(MEMBER_INFO_FILE, "r+b");
    if (fp == NULL) {
        printf("会员数据文件不存在！\n");
        return;
    }

    member_info edited;
    int found = 0;
    long pos = 0;

    // 查找会员记录
    while (fread(&edited, sizeof(edited), 1, fp) == 1) {
        if (strcmp(edited.card_num, card_num) == 0 && edited.delete_state == 0) {
            found = 1;
            pos = ftell(fp) - sizeof(edited);
            break;
        }
    }

    if (!found) {
        printf("未找到有效会员记录！\n");
        fclose(fp);
        return;
    }

    // 显示当前信息
    printf("\n当前会员信息：\n");
    printf("1.卡号：%s\n", edited.card_num);
    printf("2.姓名：%s\n", edited.name);
    printf("3.性别：%s\n", edited.s == female ? "女" : "男");
    printf("4.手机号：%s\n", edited.phone);
    printf("5.会员类型：%s\n",
           edited.mt == cika ? "次卡" :
           (edited.mt == yueka ? "月卡" : "年卡"));
    if (edited.mt == cika) {
        printf("6.剩余次数：%d\n", edited.remain_cnt);
    } else {
        printf("6.到期时间：%s", ctime(&edited.expire_time));
    }

    int op;
    printf("\n请选择要修改的项目（输入0结束修改）：");
    while (scanf("%d", &op) == 1 && op != 0) {
        switch (op) {
            case 1:
                printf("请输入新的卡号：");
                scanf("%s", edited.card_num);
                break;
            case 2:
                printf("请输入新的姓名：");
                scanf("%s", edited.name);
                break;
            case 3:
                printf("请输入新的性别（1-女,2-男）：");
                scanf("%d", (int*)&edited.s);
                break;
            case 4:
                printf("请输入新的手机号：");
                scanf("%s", edited.phone);
                break;
            case 5:
                printf("请输入新的会员类型（1-次卡,2-月卡,3-年卡）：");
                scanf("%d", (int*)&edited.mt);
                // 如果会员类型改变，需要调整相关字段
                if (edited.mt != cika) {
                    edited.remain_cnt = 0; // 非次卡没有剩余次数
                }
                break;
            case 6:
                if (edited.mt == cika) {
                    printf("请输入新的剩余次数：");
                    scanf("%d", &edited.remain_cnt);
                } else {
                    printf("请输入新的到期时间（秒数时间戳）：");
                    scanf("%ld", &edited.expire_time);
                }
                break;
            default:
                printf("无效选项！\n");
        }
        printf("请选择下一个要修改的项目（输入0结束修改）：");
    }

    // 写回文件
    fseek(fp, pos, SEEK_SET);
    fwrite(&edited, sizeof(edited), 1, fp);
    fclose(fp);
    printf("修改完成！\n");
}

